package day0613

import akka.actor.{Actor, ActorRef, ActorSystem, Props}

/**
  * @program: hadoop
  * @description: 相互发消息,并加标志位进行停止
  * @author: Qiang.Ye
  * @date: 2019-06-15 10:38
  *
  *  Ping       Pong
  *
  **/
case object PongMessage
case object PingMessage
case object StopMessage
case object StartMessage

class Pong(ping : ActorRef) extends Actor{
  var count = 0
  def incrementAndPrint {count += 1 ; println("count + 1 and pong")}
  override def receive: Actor.Receive = {
    case PingMessage =>
      if(count > 9){
        sender ! StopMessage
        context.stop(self)
        println(" count > 9")
      }else{
        println("Receive PingMessage count:"+count)
        incrementAndPrint
        sender ! PongMessage
      }
    case StartMessage =>
      println("Receive StartMessage")
      ping ! PongMessage

  }
}
class Ping extends Actor{
  override def receive: Receive = {
    case PongMessage => println("Receive PonMessage")
                        //回复一个消息
                        sender ! PingMessage
    case StopMessage => println("Stop Message")
      context.stop(self)
//      context.system.finalize()
  }
}


object Demo3 {

  def main(args: Array[String]): Unit = {
//    pong ! StartMessage
    val  system = ActorSystem("PingPongSystem")
    val  ping = system.actorOf(Props[Ping],name = "ping")
    val  pong = system.actorOf(Props(new Pong(ping)),name = "pong")

    pong ! StartMessage
  }


}
